package com.keda.util;

import com.keda.model.Product;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class DBUtil {

    public static Connection createConnection() {

        Connection connection = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/db_ebuys?" +
                    "serverTimezone=Asia/Shanghai&useUnicode=true" +
                    "&characterEncoding=utf8&useSSL=false";;
            String user = "root";
            String password = "123456"; // 硬编码，不推荐
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static <T> List<T> executeQuery(String sql, Class<T> clazz, Object... params) {
        Connection connection = createConnection();
        List<T> result = executeSQL(connection, sql,
                new BeanListHandler<>(clazz), params);
        return result;
    }

    public static <T> T executeObjectQuery(String sql, Class<T> clazz, Object... params) {
        Connection connection = createConnection();
        T result = executeSQL(connection, sql, new BeanHandler<>(clazz), params);
        return result;
    }

    public static <T> T executeQuery(String sql, Object... params) {
        Connection connection = createConnection();
        T result = executeSQL(connection, sql, new ScalarHandler<>(), params);
        return result;
    }


    /**
     * 执行查询
     * @param connection
     * @param sql
     * @param resultSetHandler
     * @return
     * @param <T>
     */
    public static <T> T executeSQL(Connection connection, String sql,
                                    ResultSetHandler<T> resultSetHandler, Object... params) {
        QueryRunner queryRunner = new QueryRunner();
        T result = null;
        try {
            result = queryRunner.query(connection, sql, resultSetHandler, params);
        } catch (SQLException e) {
            throw new RuntimeException("查询失败");
        } finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException("查询失败");
            }
        }
        return result;
    }


}
